package com.bc.web.interceptors;



import javax.servlet.http.HttpServletRequest;

import com.bc.web.model.AdminUser;
import com.bc.web.model.MerchUser;
import com.bc.web.model.OrgUser;
import com.fs.common.bean.FSDWZRespon;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;

/**
 * 全局拦截器,主要记录操作日志,登录超时验证
 * @author 钟展峰
 *
 * 2015年8月25日
 */
public class SessionTimeOutInterceptor implements Interceptor {
	
	private static final String ADMIN_ACTION = "/admin";
	private static final String ORG_ACTION = "/org";
	private static final String MERCH_ACTION = "/merch";
	
	@Override
	public void intercept(Invocation inv) {
		Controller ctr = inv.getController();
		String actionKey = inv.getActionKey();
		
		if(actionKey.startsWith(ADMIN_ACTION)){
			processAdmin(inv,ctr);
		}else if(actionKey.startsWith(ORG_ACTION)){
			processOrg(inv,ctr);
		}else if(actionKey.startsWith(MERCH_ACTION)){
			processMerch(inv, ctr);
		}else {
			inv.invoke();
		}
	}
	
	private void processAdmin(Invocation inv, Controller ctr){
		AdminUser loginUser = (AdminUser) ctr.getSession().getAttribute("loginUser");
		if(loginUser != null){
			inv.invoke();
			return;
		}
		if(isAjaxRequest(ctr.getRequest())){
			ctr.renderJson(FSDWZRespon.getTimeOut());
		}else{
			ctr.redirect("/admin/loginpage");
		}
	}
	
	private void processOrg(Invocation inv,Controller ctr){
		OrgUser loginUser = (OrgUser) ctr.getSession().getAttribute("orgUser");
		if(loginUser != null){
			inv.invoke();
			return;
		}
		if(isAjaxRequest(ctr.getRequest())){
			ctr.renderJson(FSDWZRespon.getTimeOut());
		}else{
			ctr.redirect("/org/loginpage");
		}
	}
	
	private void processMerch(Invocation inv,Controller ctr){
		MerchUser loginMerchUser = (MerchUser) ctr.getSession().getAttribute("merchUser");
		if(loginMerchUser != null){
			inv.invoke();
			return;
		}
		if(isAjaxRequest(ctr.getRequest())){
			ctr.renderJson(FSDWZRespon.getTimeOut());
		}else{
			ctr.redirect("/merch/loginpage");
		}
	}
	
	private boolean isAjaxRequest(HttpServletRequest request) {
		String requestType = request.getHeader("X-Requested-With");
		return ("XMLHttpRequest").equals(requestType);
	}
}
